package org.example.task.controller;


import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.task.converter.PermissionConverterMapper;
import org.example.task.model.dto.PageDTO;
import org.example.task.model.dto.permission.InsertPermissionDTO;
import org.example.task.model.dto.permission.UpdatePermissionDTO;
import org.example.task.model.po.Permission;
import org.example.task.model.query.PermissionPageQuery;
import org.example.task.model.vo.R;
import org.example.task.model.vo.permission.PermissionVO;
import org.example.task.service.IPermissionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 权限模块
 *
 * @module 权限模块
 */
@RestController
@RequestMapping("/permission")
@RequiredArgsConstructor
public class PermissionController {
    private final IPermissionService permissionService;
    private final PermissionConverterMapper permissionConverterMapper;

    /**
     * 查询权限列表
     *
     * @param permissionPageQuery 分页查询条件
     * @return 查询结果
     */
    @PreAuthorize("hasAuthority('permission_list')")
    @GetMapping("/list")
    public R<PageDTO<PermissionVO>> getPermissions(@Valid @RequestBody PermissionPageQuery permissionPageQuery) {
        PageDTO<PermissionVO> permissionVOPageDTO = permissionService.getPermissionPage(permissionPageQuery);
        return R.success(permissionVOPageDTO);
    }

    /**
     * 添加权限
     *
     * @param permissionDTO 新增权限数据
     * @return 结果
     */
    @PreAuthorize("hasAuthority('permission_create')")
    @PostMapping
    public R addPermission(@Valid @RequestBody InsertPermissionDTO permissionDTO) {
        Permission permission = permissionConverterMapper.insertPermissionDTOToPermission(permissionDTO);
        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());
        if (permissionService.save(permission)) {
            return R.success();
        }
        return R.error("添加失败");
    }

    /**
     * 修改权限
     *
     * @param permissionDTO 更新信息
     * @return 结果
     */
    @PreAuthorize("hasAuthority('permission_edit')")
    @PutMapping
    public R updatePermission(@Valid @RequestBody UpdatePermissionDTO permissionDTO) {
        Permission permission = permissionConverterMapper.updatePermissionDTOToPermission(permissionDTO);
        permission.setUpdateTime(LocalDateTime.now());
        if (permissionService.updateById(permission)) {
            return R.success();
        }
        return R.error("修改失败");
    }

    /**
     * 删除权限
     *
     * @param permissionId 删除id
     * @return 结果
     */
    @PreAuthorize("hasAuthority('permission_delete')")
    @DeleteMapping
    public R deletePermission(@RequestParam Long permissionId) {
        if (permissionService.removeById(permissionId)) {
            return R.success();
        }
        return R.error("删除失败");
    }
}
